<?php
class Tag
{
	public static function number2ip($num)
	{
		return Util::number2ip($num);
	}
	
	public static function dateFormat($date,$format='Y-m-d H:i:s')
	{
		if(!is_numeric($date))
		{
			$date = strtotime($date);
		}
		
		return date($format,$date);
	}
	
	public static function cnTruncate($string,$length,$etc='',$nl2br=false)
	{
		$result = '';
		$string = html_entity_decode(trim(str_replace("　","",str_replace("&nbsp;","",strip_tags($string)))),   ENT_QUOTES,   'UTF-8');
		$strlen = strlen($string);
		for($i = 0; (($i < $strlen) && ($length > 0)); $i++)
		{
			if($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
			{
				if($length   <   1.0)   
				{
					break;
				}
		
				$result .= substr($string, $i, $number);
				$length -= 1.0;
		
				$i += $number - 1;
			}
			else
			{
				$result .= substr($string, $i, 1);
				$length -= 0.5;
			}
		}
		
		$result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
		
		if($i < $strlen)
		{
			$result .= $etc;
		}
		
		if($nl2br)
		{
			$result = nl2br($result);
		}
		
		return $result;
	}
	
	public static function getAdList($position)
	{
		$system = Util::loadSystemData();
		
		if(!array_key_exists($position, $system['ad']))
		{
			return false;
		}
		
		return $system['ad'][$position];
	}
	
	public static function getModuleList($position, $cacheTime = 600)
	{
		if(empty($cachePosition))
		{
			$cachePosition = 'all';
		}
		
		$moduleService = new BaseDbService('module');
		
		//从缓存中取
		$update = false;
		$key = 'module_'.$position;
		$modules = C('LtCache')->get($key);
		if($modules===false)
		{
			//从数据库中加载
			$update = true;
			$modules = $moduleService->rows(array('position'=>$position), 'orderby DESC,id ASC');
			foreach($modules as &$lv)
			{
				$lv['data'] = json_decode($lv['data'], true);
			}
		}
		
		foreach($modules as &$module)
		{
			if(empty($module['data']) || $module['data']['expire']<time())
			{
				$update = true;
				//TODO 重新获取数据，保存到数据库中
				$data = array();
				
				$shareService = new ShareService();
				$tmp = $shareService->query(array('tag'=>$module['tags']), 1, $module['page_size']);
				if(!empty($tmp['list']))
				{
					$data = $tmp['list'];
				}
				$update = array('expire'=>time()+$module['update_period']*3600,'value'=>$data);
				$moduleService->update($module['id'], array('data'=>json_encode($update)));
				
				$module['data'] = $update;
			}
		}
		
		if(!empty($modules) && $update)
		{
			C('LtCache')->update($key, $modules, $cacheTime);
		}
	
		return $modules;
	}
	
	public function getCateogryLevelsById($categoryId)
	{
		//从缓存中取
		$cacheTime = 600;
		$key = 'category_level_'.$categoryId;
		$levels = C('LtCache')->get($key);
		if($levels!==false)
		{
			return $levels;
		}
		
		$levels = C('CategoryService')->getCateogryLevelsById($categoryId);
		if($levels!==false)
		{
			C('LtCache')->update($key, $levels, $cacheTime);
		}
		
		return $levels;
	}
}